package site.duanzy;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import site.duanzy.upload.ProgressEntity;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * @author leo
 * @date 2018/7/23 14:39
 */
@Controller
public class FileUploadController {

    @RequestMapping(value = "/touploadfile", method = RequestMethod.GET)
    public ModelAndView toUpload(HttpServletRequest request,
                                 HttpServletResponse response) throws Exception{
        return new ModelAndView("upload");

    }

    @ResponseBody
    @RequestMapping(value = "/touploadfile2", method = RequestMethod.GET)
    public String toUpload2(HttpServletRequest request,
                                 HttpServletResponse response) throws Exception{
        return "upload";

    }

    @RequestMapping(value = "/touploadfile3", method = RequestMethod.GET)
    public String toUpload3() throws Exception{
        return "upload";
    }

    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index() throws Exception{
        return "index";
    }


    /**
     * upload  上传文件
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/uploadfile2", method = RequestMethod.POST)
    public ModelAndView upload(HttpServletRequest request,
                               HttpServletResponse response) throws Exception {
        final HttpSession hs = request.getSession();
        ModelAndView mv = new ModelAndView();
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if(!isMultipart){
            return mv;
        }
        // Create a factory for disk-based file items
        FileItemFactory factory = new DiskFileItemFactory();

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
//        upload.setProgressListener(new ProgressListener(){
//            @Override
//            public void update(long pBytesRead, long pContentLength, int pItems) {
//                ProcessInfo pri = new ProcessInfo();
//                pri.itemNum = pItems;
//                pri.readSize = pBytesRead;
//                pri.totalSize = pContentLength;
//                pri.show = pBytesRead+"/"+pContentLength+" byte";
//                pri.rate = Math.round(new Float(pBytesRead) / new Float(pContentLength)*100);
//                hs.setAttribute("proInfo", pri);
//            }
//        });
        List<FileItem> items = upload.parseRequest(request);
        String path = request.getSession().getServletContext().getRealPath("upload");
        System.out.println(path);

        for(FileItem item : items){
            if(item.isFormField()){

            }else{
                System.out.println(path +"/"+  item.getFieldName());
                File targetFile = new File(path +"/"+ item.getName());
                if(!targetFile.exists()){
                    targetFile.createNewFile();
                }
                item.write(targetFile);
            }
        }
        System.out.println("上传文件的个数为：" + items.size());
        return mv;
    }

    /**
     * 实现文件上传
     * */
    @RequestMapping("fileUpload")
    @ResponseBody
    public String fileUpload(@RequestParam("file") MultipartFile file){
        if(file.isEmpty()){
            return "false";
        }
        String fileName = file.getOriginalFilename();
        int size = (int) file.getSize();
        System.out.println(fileName + "-->" + size);

        String path = "C:\\java\\idea_workspace\\uploadfile\\src\\main\\webapp\\upload" ;
        File dest = new File(path + "/" + fileName);
        if(!dest.getParentFile().exists()){ //判断文件父目录是否存在
            dest.getParentFile().mkdir();
        }
        try {
            file.transferTo(dest); //保存文件
            return "true";
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "false";
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "false";
        }
    }

    /**
     * process 获取进度
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/process", method = RequestMethod.GET)
    @ResponseBody
    public Object process(HttpServletRequest request,
                          HttpServletResponse response) throws Exception {
        ProgressEntity status = (ProgressEntity) request.getSession().getAttribute("status");
        return status;
    }

    class ProcessInfo{
        public long totalSize = 1;
        public long readSize = 0;
        public String show = "";
        public int itemNum = 0;
        public int rate = 0;
    }

}
